//设置数据
import _array from "../utils/_array";
import _object from "../utils/_object";

let __set = function (nodes, checks, ids, primary) {

    if (nodes.length > 0)
    {
        for (let i = 0, l = nodes.length; i < l; i++)
        {
            if (nodes[i].hasOwnProperty('children') && nodes[i].children.length > 0)
            {
                __set(nodes[i].children, checks, ids, primary);
            }
            else if (_object._length(checks) > 0 && checks.indexOf(nodes[i][primary].toString()) > -1)
            {
                //最底层
                ids.push(nodes[i][primary]);
            }
        }
    }
};


let _tree = {

    //设置选中节点
    set : function (checks, nodes, that, key = 'bind_ref', primary = 'id') {
        if (typeof checks == "string")
            checks = checks ? checks.split(",") : [];
        else if (typeof checks == "number")
            checks = [ checks.toString() ];

        let ids = [];
        __set(nodes, checks, ids, primary);


        //选中
        that.$nextTick(() => {
            if (that.$refs[key]){
                that.$refs[key].setCheckedKeys(ids);
                return
            }

            setTimeout(() => {
                that.$refs[key].setCheckedKeys(ids);
            }, 1)
        })
    },

    //获取选中节点
    get: function (that, refsName = 'bind_ref') {
        let node_ids = that.$refs[refsName].getCheckedKeys()
        let half_node_ids = that.$refs[refsName].getHalfCheckedKeys()
        return  _array._de_merge(node_ids, half_node_ids)
    },

    //设置叶子节点
    set_leaf: function(checks, that, key = 'bind_ref'){

        if (typeof checks == "string")
            checks = checks ? checks.split(",") : [];
        else if (typeof checks == "number")
            checks = [ checks.toString() ];

        //选中
        that.$nextTick(function(){
            that.$refs[key].setCheckedKeys(checks);
        })
    },

    //获取选中叶子节点
    get_leaf: function (that, refsName = 'bind_ref') {
        //仅返回叶子节点
        return  that.$refs[refsName].getCheckedKeys(true)
    },

    //设置级联选择器
    set_cascader : function (that) {

    },

    //获取级联选择器
    get_cascader : function (that, refsName = 'bind_ref') {

        let ids = [];
        let node_ids = that.$refs[refsName].getCheckedNodes(true)
        if (_object._length(node_ids) > 0)
        {
            for (let i in node_ids)
            {
                ids.push(node_ids[i].value);
            }
        }
        return  _array._unique(ids);
    },
};

export default _tree
